package com.example.demo.advice;

import java.util.HashMap;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

@ControllerAdvice
public class GlobalExceptionHandler {
	
	private static final Logger logger = LogManager.getLogger(GlobalExceptionHandler.class);
	
	@ResponseBody
	@ExceptionHandler(RuntimeException.class)
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	public Map<String, Object> xRuntimeException(Exception e) {
		e.printStackTrace();
		Map<String, Object> res = new HashMap<String, Object>();
		res.put("code", 400);
		String message = e.toString().replace("java.lang.RuntimeException: ", "");
		if(message.indexOf("Exception:") > -1 || message.indexOf("java") > -1) {
			res.put("code", 500);
			message = "SERVER EXCEPTION";
			logger.error("xRuntimeException:", e);
		}
		logger.error("xRuntimeException:" + e.getMessage());
		res.put("message", message);
		return res;
	}
}
